<?php
namespace app\api\controller;

use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Text;
use weixin\Weixin as Wx;

class Weixin
{

    //用户首次配置开发环境  
    public function entry()  
    {  
    	// file_put_contents('../runtime/input.log', file_get_contents('php://input').PHP_EOL, FILE_APPEND);
        $signature = input("signature");  
        $timestamp = input("timestamp");  
        $nonce     = input("nonce");  
        $echostr   = input('echostr');        
	    $token     = 'dydh';  
	    $tmpArr    = array($token, $timestamp, $nonce);  
	    sort($tmpArr, SORT_STRING);  
	    $tmpStr    = implode( $tmpArr );  
	    $tmpStr    = sha1( $tmpStr );  
	    if( $tmpStr == $signature && $echostr)  
	    {  
	    	echo $echostr;  
	    }else{  
	        $this->resWeixin();
	    }  
    }  


	function resWeixin(){
		$app = new Application(config('weixin.haitou'));
		// 从项目实例中得到服务端应用实例。
		$server = $app->server;
		$server->setMessageHandler(function ($message) {
			$type = $message->MsgType;
			$weixin = new Wx();
			$weixin->$type($message);
		});

		$server->serve()->send();
	}

	//获取微信用户信息
	public function login(){

		$state = input('redirect_uri', '');

		$redirect_uri = urlencode ('http://dhclub.tigerisa.com/api/weixin/get_info');

		$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('weixin.enterpriser')['app_id'].'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state='.$state.'#wechat_redirect';

		header('Location: ' . $url);exit;
	}

	public function get_info(){
		$app = new Application(config('weixin.enterpriser'));
		$oauth = $app->oauth;
		// 获取 OAuth 授权结果用户信息
		$user = $oauth->user();
		
		$url = urldecode(input('state', '')).'?id='.$user->getId().'&name='.$user->getName().'&img='.$user->getAvatar();

		header('location:'. $url); exit;
	}

}
